package com.zhao.controller.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhao.Util.FileSize;
import com.zhao.comm.log.MyLog;
import com.zhao.pojo.Datafile;
import com.zhao.pojo.Filestatistic;
import com.zhao.pojo.Filegroup;
import com.zhao.pojo.User;
import com.zhao.service.DatafileService;
import com.zhao.service.FileStatisticService;
import com.zhao.service.FilegroupService;
import com.zhao.service.RoleService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/file")
public class FileController {

    @Autowired
    DatafileService datafileService;
    @Autowired
    FilegroupService filegroupService;
    @Autowired
    FileStatisticService fileStatisticService;
    @Autowired
    RoleService roleService;
    //资源管理
    @RequestMapping("/data_file")
    public String fileQuery(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
                            @RequestParam(value = "size",required = false,defaultValue = "5")Integer size,
                            @RequestParam(value = "title",required = false)String title,
                            Model model) {
        //判断当前用户身份 用户查自己 管理员和 超级管理员 查全部
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
        String roleName=roleService.getUserRoleName(loginUser.getUserId());
        String author=null;
        if (roleName.equals("用户")){
            author=loginUser.getUserAccount();
        }
        Page<Datafile> page=datafileService.selectListPage(pageNum, size,title,author,null);
        model.addAttribute("files",page);
        return "admin/data_file";
    }

    //上传文件页
    @RequestMapping("/add_file")
    public String addFile(Model model){
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<Filegroup> wrapper = new QueryWrapper<Filegroup>();
        wrapper.eq("uid",loginUser.getUserId());
        Collection<Filegroup> filegroups = filegroupService.list(wrapper);
        model.addAttribute("filegroups",filegroups);
        return "admin/add_file";
    }

    @RequestMapping("/newGroup")
    @ResponseBody
    public String newGroup(Filegroup filegroup, Model model){
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
        filegroup.setUid(loginUser.getUserId());
        filegroupService.save(filegroup);
        Collection<Filegroup> filegroups = filegroupService.list(null);
        model.addAttribute("filegroups",filegroups);
        return "1";
    }

    //修改查询一条
    @GetMapping("/editFile/{id}")
    public String editFile(@PathVariable("id")Integer id,Model model){
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<Filegroup> wrapper = new QueryWrapper<Filegroup>();
        wrapper.eq("uid",loginUser.getUserId());

        Datafile byId = datafileService.getById(id);
        List<Filegroup> list = filegroupService.list(wrapper);
        model.addAttribute("b",byId);
        model.addAttribute("groups",list);
        return "admin/update_file";
    }
    //@MyLog(value = "修改资源信息")
    @PostMapping("/updateFile")
    public String editFile(Datafile datafile){
        Datafile byId = datafileService.getById(datafile.getFileId());
        System.out.println(datafile.toString());
        System.out.println(byId.toString());
        Filegroup old = filegroupService.getById(byId.getFilegroupId());
        //System.out.println("=================================1>"+old.getGnum());
        old.setGnum(old.getGnum()-1);
        filegroupService.updateById(old);
        //System.out.println("=================================2>"+old.getGnum());
        Filegroup news = filegroupService.getById(datafile.getFilegroupId());
        //System.out.println("=================================3>"+news.getGnum());
        news.setGnum(news.getGnum()+1);
        filegroupService.updateById(news);
        //System.out.println("=================================4>"+news.getGnum());
        byId.setTitle(datafile.getTitle());
        byId.setFilegroupId(datafile.getFilegroupId());
        byId.setDescription(datafile.getDescription());
        byId.setPrice(datafile.getPrice());
        datafileService.updateById(byId);
        return "redirect:/file/data_file";
    }

    //@MyLog(value = "删除资源")
    @GetMapping("/delFile/{id}")
    public String delFile(@PathVariable("id")Integer id){
        Datafile one = datafileService.getById(id);
        //修改组数量
        Filegroup byId = filegroupService.getById(one.getFilegroupId());
        byId.setGnum(byId.getGnum()-1);
        filegroupService.updateById(byId);
        //删除本地文件
        boolean flag=false;
        if (one!=null){
            File file = new File(one.getAbsolutepath());
            if (file.exists()) {
                file.delete();
                System.out.println("文件已经被成功删除");
                flag=true;
            }
        }
        if (flag){
            System.out.println(id);
            //删除 资源信息统计表中对应数据
            fileStatisticService.remove(new QueryWrapper<Filestatistic>().eq("file_id",id));
            //删除 数据
            datafileService.removeById(id);
        }
        return "redirect:/file/data_file";
    }
    //@MyLog(value = "资源上传")
    @RequestMapping("/fileupload")
    @ResponseBody
    public String upload(Datafile datafile, MultipartFile file) throws IOException {

        if (datafile.getTitle().isEmpty()){
            JSONObject resObj = new JSONObject();
            resObj.put("msg", "error");
            return  JSONArray.toJSONString(resObj);
        }
        System.out.println("===================================>"+datafile);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
        String res = sdf.format(new Date());

        // uploads文件夹位置
        //String rootPath = request.getSession().getServletContext().getRealPath("resource/uploads/");
        //String rootPath =System.getProperty("user.dir")+"/src/main/resources/uploads/ziyuan/";
        String rootPath =System.getProperty("user.dir")+"/upload/ziyuan/";
        //获取文件大小
        String size = FileSize.FormetFileSize(file.getSize());
        // 原始名称
        String originalFileName = file.getOriginalFilename();
        // 新文件名
        String newFileName = "sliver" + res + originalFileName.substring(originalFileName.lastIndexOf("."));
        // 创建年月文件夹
        Calendar date = Calendar.getInstance();
        File dateDirs = new File(date.get(Calendar.YEAR) + File.separator + (date.get(Calendar.MONTH)+1));

        // 新文件
        File newFile = new File(rootPath + File.separator + dateDirs + File.separator + newFileName);
        // 判断目标文件所在目录是否存在
        if( !newFile.getParentFile().exists()) {
            // 如果目标文件所在的目录不存在，则创建父目录
            newFile.getParentFile().mkdirs();
        }
        System.out.println(newFile);
        // 将内存中的数据写入磁盘
        file.transferTo(newFile);
        // 完整的url
        String fileUrl = date.get(Calendar.YEAR) + "/" + (date.get(Calendar.MONTH)+1) + "/" + newFileName;
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
        //存储数据库
        datafile.setOldname(originalFileName);//原名
        datafile.setNewname(newFileName);//新名
        datafile.setAbsolutepath(newFile.getPath());//绝对路径
        datafile.setRelativepath(fileUrl);//相对路径
        datafile.setFilesize(size);//大小
        datafile.setAuthor(loginUser.getUserAccount());
        datafile.setType(originalFileName.substring(originalFileName.lastIndexOf(".")+1));
        //添加最新资源
        datafileService.save(datafile);
        //获取最新资源 取id
        QueryWrapper<Datafile> inSql = new QueryWrapper<Datafile>().inSql("file_id", "select max(file_id) from datafile");
        Datafile one = datafileService.getOne(inSql);
        //向组添加数据
        Filegroup filegroup = filegroupService.getById(one.getFilegroupId());
        filegroup.setGnum(filegroup.getGnum()+1);
        filegroupService.updateById(filegroup);
        //创建最新资源表
        Filestatistic fileStatistic=new Filestatistic();
        fileStatistic.setFileId(one.getFileId());
        //添加最新 资源的 资源统计表
        fileStatisticService.save(fileStatistic);
        //查统计表 通过资源id 获取 统计表id 对 资源表进行双向绑定
        Filestatistic statistic = fileStatisticService.getOne(new QueryWrapper<Filestatistic>().eq("file_id", one.getFileId()));
        one.setBrowse(statistic.getId()+"");
        datafileService.updateById(one);
        JSONObject resObj = new JSONObject();
        resObj.put("msg", "ok");
        return  JSONArray.toJSONString(resObj);
    }

}
